package repository

import (
	"buding-ai/internal/core"
	"buding-ai/internal/repository/model"
	"gorm.io/gorm"
	"sync"
)

var (
	chatRepos *ChatRepository
	chatOnce  sync.Once
)

type ChatRepository struct {
	db *gorm.DB
}

func GetChatRepository() *ChatRepository {
	chatOnce.Do(func() {
		chatRepos = &ChatRepository{
			db: core.DB,
		}
	})
	return chatRepos
}

func (r *ChatRepository) InitChat(id uint, name string) (*model.Chat, error) {
	if name == "" {
		name = "新的对话"
	}
	chat := model.NewChat(name, id)
	if tx := r.db.Create(chat); tx.Error != nil {
		return nil, tx.Error
	}
	return chat, nil
}
